package page;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import ressource.CadreProduit;

/**
 * Servlet implementation class Recherche
 */
public class Recherche extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Recherche() {
        super();
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doSearch(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doSearch(request, response);
	}
	
	private void doSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String motif = request.getParameter("motif");
		String type = request.getParameter("type");
		Connection con = null;
		List<CadreProduit> produits = new ArrayList<CadreProduit>();
		CadreProduit p;
		RequestDispatcher dis;
		ServletContext context = getServletContext();
		
		if(motif == null && type == null) {
			dis=request.getRequestDispatcher("home");
			dis.forward(request,response);
			return;
		}
		request.setAttribute("recherche", motif);
		
		try{
			Context namingContext = new InitialContext();
			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
			con = dataSource.getConnection();
			ResultSet rs;
			
			//Calcul dynamique de la requete de recherche
			StringBuffer sb = new StringBuffer();
			if(motif != null && !motif.isEmpty()) {
				//Est ce que j'ai plusieurs mots ?
				String[] tmpMotif = motif.split(" ");
				if(tmpMotif.length-1 > 0) {
					sb.append("AND (p.intitule LIKE '%");
					int max = motif.length();
					for(int i = 0; i < max; ++i) {
						Character tmpChar = motif.charAt(i);
						if(motif.charAt(i) == ' ') {
							sb.append("%' COLLATE utf8_unicode_ci ");
							if(i < max-1)
								sb.append(" OR p.intitule LIKE '%");
						} else {
							sb.append(tmpChar);
						}
					}
					sb.append("%' COLLATE utf8_unicode_ci) ");
				} else {
					sb.append("AND `p`.intitule LIKE ");
					sb.append("'%"+motif+"%' ");
					sb.append("  COLLATE utf8_unicode_ci ");
				}
			}
			if(type != null && !type.isEmpty()) {
				Integer iType = Integer.parseInt(type);
				sb.append("AND `tp`.id_type=");
				sb.append(iType.toString()+" ");
			}
			
			PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) AS nb_results FROM `produit` p, `type_produit` tp WHERE `p`.id_type = `tp`.id_type " + sb.toString());
			
			Integer nb_results = 0;
			rs = pstmt.executeQuery();
			if(rs.next()){
				nb_results = rs.getInt("nb_results");
				rs.close();
			}
			
			sb.append("ORDER BY prix_min DESC ");
			sb.append("LIMIT ?, ?");
			pstmt=con.prepareStatement("SELECT `p`.id_produit,`tp`.nom, `p`.intitule, `p`.description, `p`.photo, (SELECT a2.prix FROM annonce a2 WHERE a2.id_produit = p.id_produit ORDER BY prix ASC LIMIT 0,1) as prix_min, (SELECT COUNT(*) FROM annonce WHERE annonce.id_produit = p.id_produit) as nb_annonce FROM `produit` p, `type_produit` tp WHERE `p`.id_type = `tp`.id_type " + sb.toString());
			
			//On gere la pagination :
			Integer resultspage = 20;
			Integer i=0;
			try{
				resultspage = Integer.parseInt(context.getAttribute("nbresults").toString());
				if(request.getParameter("page") != null)
					i = Integer.parseInt(request.getParameter("page")) - 1;
			}catch(NumberFormatException e){
				i = 0;
			}
			if(i < nb_results / resultspage ) {
				int buff = i * resultspage;
				pstmt.setInt(1, buff);
				pstmt.setInt(2, resultspage);
			}
			else{
				pstmt.setInt(1, 0);
				pstmt.setInt(2, resultspage);
			}
			request.setAttribute("nb_results", (int)nb_results/resultspage);
			request.setAttribute("page", i+1);
			
			rs = pstmt.executeQuery();
			while(rs.next()){
				p = new CadreProduit();
				p.setId(rs.getInt("id_produit"));
				p.setType(rs.getString("nom"));
				p.setIntitule(rs.getString("intitule"));
				p.setDescription(rs.getString("description"));
				p.setPhoto(rs.getString("photo"));
				p.setPrixMin(rs.getInt("prix_min"));
				p.setNbAnnonces(rs.getInt("nb_annonce"));
				produits.add(p);
			}
			rs.close();
			request.setAttribute("produits", produits);
			
			//Renvoyons les informations de la recherche :
			if(type != null && !type.isEmpty()) {
				String requete = "SELECT nom FROM type_produit WHERE id_type = ?";
				pstmt=con.prepareStatement(requete);
				pstmt.setInt(1, Integer.parseInt(type));
				rs = pstmt.executeQuery();
				if(rs.next()) {
					request.setAttribute("type", rs.getString("nom"));
					request.setAttribute("idType", type);
				}
				rs.close();
			}
			
			//Et la liste des catégories :
			pstmt = con.prepareStatement("SELECT * FROM `type_produit`");
			rs = pstmt.executeQuery();
			Map<Integer, String> types = new LinkedHashMap<Integer, String>();
			while(rs.next()){
				types.put(rs.getInt("id_type"), rs.getString("nom"));
			}			
			request.setAttribute("types", types);
		}catch(Exception e){
			e.printStackTrace();
		} finally {
			try {
				if(con != null) con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		dis=request.getRequestDispatcher("recherche.jsp");
		dis.forward(request,response);
	}
}
